package com.qidianit.check.login;

import com.qidianit.mes.common.pojo.MesResult;
import com.qidianit.mes.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2025/8/7 9:58
 * @description
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    // 远程调用请求查询用户信息
    @Autowired
    @Qualifier("checkRestTemplate")
    private RestTemplate checkRestTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        System.out.println("登录拦截器拦截了请求：" + url);
        // 从请求头中获取token
        String token = request.getHeader("token");
        System.out.println(token);
        if(token != null && !"".equals(token)){
            if(JwtUtil.validateToken(token)){
                System.out.println("登录验证通过");
                String idStr = JwtUtil.getClaimFromToken(token, "id").toString();
                Integer id = Integer.parseInt(idStr);
                // 这里的请求路径应该写在配置文件中的，我这里节省时间，就直接写死了
                MesResult forObject = checkRestTemplate.getForObject("http://localhost:11011/sys/user/" + id, MesResult.class);
                // 将用户信息放到request作用域中
                request.setAttribute("loginUser",forObject.getData());
                // 验证通过，放行
                return true;
            }
        }
        return true;
    }
}
